package it.infodea.tapestrydea.components.livegrid;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.RenderSupport;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.IncludeStylesheet;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.corelib.components.ModifiedGrid;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

@IncludeStylesheet("LGrid.css")
public class LGrid extends ModifiedGrid {
	
	public static final String REMOVE_COLUMN_NAME = "lGridRemoveCell";

	@Parameter(required=true)
	private Class beanClass;
	
	@Parameter(required=false)
	private Object bean;
	
	@Parameter
	private String removeLabel = "Remove";
	
	@Parameter(value="true")
	private boolean hideFormLabel;
	
	@SuppressWarnings("unused")
	@Component(parameters = { "rowIndex=inherit:rowIndex",
			"columnIndex=inherit:columnIndex", "rowClass=inherit:rowClass",
			"rowsPerPage=rowsPerPage", "currentPage=currentPage", "row=row",
			"overrides=overrides", "volatile=inherit:volatile",
			"encoder=inherit:encoder", "lean=inherit:lean", 
			"zone=componentResources.id", "removeLabel=inherit:removeLabel"})
	private LGridRows rows;

	@SuppressWarnings("unused")
	@Component(parameters = { "rowClass=inherit:rowClass", "overrides=overrides",
			"zone=componentResources.id", "row=row", "object=inherit:bean"})
	private LGridInsertRow insertRow;
	
	@SuppressWarnings("unused")
	@Component(parameters = { "index=inherit:columnIndex", "lean=inherit:lean",
			"overrides=overrides", "zone=zone" })
	private LGridColumns columns;
	
	@Inject
	private BeanModelSource modelSource;
	
	@Inject
	private Messages messages;
	
	@Inject
	private ComponentResources resources;
	
	@Inject
	private RenderSupport support;
	
	@Inject
	@Path("LGrid.css")
	private Asset hideLabelStyle;
	
	@SetupRender
	void setup(){
		if(hideFormLabel){
			support.addStylesheetLink(hideLabelStyle, "all");
		}
	}

	public boolean isEmpty(){
		return super.getDataSource() == null || super.getDataSource().getAvailableRows() == 0;
	}
	
	public BeanModel<?> getDataModel(){
		BeanModel<?> dataModel = null;
		if(super.getDataSource() != null/* && super.getDataSource().getAvailableRows() > 0*/){
			dataModel = super.getDataModel();
		}else{
			dataModel = modelSource.createDisplayModel(beanClass, messages);
		}
		if(!dataModel.getPropertyNames().contains(REMOVE_COLUMN_NAME))
			dataModel.add(REMOVE_COLUMN_NAME, null);
		return dataModel;
	}
	
 }
